package org.csu.mypetstore.controller;

import net.sf.json.JSONObject;
import org.csu.mypetstore.domain.Sentence;
import org.csu.mypetstore.service.TalkService;
import org.csu.mypetstore.service.impl.TalkServiceImpl;
import org.csu.mypetstore.tools.talkPart.WebSocketServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/talk")
public class TalkController {
    @Autowired
    private TalkService talkService = new TalkServiceImpl();

    @GetMapping
    @ResponseBody
    public String get(String type,String username){
        if(type.equals("name"))
        {
            JSONObject object = new JSONObject();
            object.put("status","OK");
            object.put("msg","获取对话列表成功!");
            object.put("data",talkService.getNameList());
            return object.toString();
        }
        else if(type.equals("talk"))
        {
            JSONObject object = new JSONObject();
            object.put("status","OK");
            object.put("msg","获取对话列表成功!");
            object.put("data",talkService.getTalkList(username));
            return object.toString();
        }
        else{
            JSONObject object = new JSONObject();
            object.put("status","NOK");
            object.put("msg","传入参数类型错误!");
            object.put("data",null);
            return object.toString();
        }
    }

    @PostMapping
    @ResponseBody
    public String insert(Sentence sentence){
        try {
            WebSocketServlet.sendInfo(sentence);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = talkService.insertSentence(sentence);
        if(s.equals("发送成功!")){
            JSONObject object = new JSONObject();
            object.put("status","OK");
            object.put("msg","发送成功!");
            object.put("data",null);
            return object.toString();
        }
        else
        {
            JSONObject object = new JSONObject();
            object.put("status","NOK");
            object.put("msg","发送失败!");
            object.put("data",null);
            return object.toString();
        }
    }
}
